package ldh.im.handle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import ldh.im.ImConfig;
import ldh.im.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

@ChannelHandler.Sharable
public class ImCheckHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImCheckHandler.class);

    private static final byte AUTHED = 0b01110000;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ByteBuf)) {
            ctx.fireChannelRead(msg);
            return;
        }
        ByteBuf byteBuf = (ByteBuf) msg;
        if (byteBuf.readableBytes() > 5) {
            byteBuf.markReaderIndex();
            boolean checkVersion = checkVersion(ctx, byteBuf);
            if (!checkVersion) {
                error(ctx, "非法返回");
                return;
            }
        }
//        byteBuf.setByte(0, AUTHED);
        ctx.fireChannelRead(byteBuf);
    }

    protected boolean checkVersion(ChannelHandlerContext ctx, ByteBuf byteBuf) {
        byte b = byteBuf.getByte(0);
        boolean isCheck = ByteUtil.getHighFour(b) == AUTHED;
        if (isCheck) return true;

        boolean checkIm = checkImHeader(b, byteBuf.getShort(1));
        if (!checkIm) {
            return false;
        }
        return true;
    }

    protected boolean checkImHeader(byte b, short vo) {
        int lowValue = ByteUtil.getLowFour(b);
        boolean isTrue = lowValue == ImConfig.SERVER_CODE;
        if (!isTrue) {
            LOGGER.error("版本信息不正确：实际值：{}，应该值：{}, 类型： {}", lowValue, ImConfig.SERVER_CODE, vo);
        }
        return isTrue;
    }

    protected void error(ChannelHandlerContext ctx, String message) {
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        LOGGER.error("非法请求, ip: {}", inetSocketAddress.getAddress());
//        throw new RuntimeException(message);
    }
}